package collecion.nexd.com.newnexdcollection.presenter;

import android.annotation.TargetApi;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.telephony.CellInfo;
import android.telephony.CellInfoCdma;
import android.telephony.CellInfoGsm;
import android.telephony.CellInfoLte;
import android.telephony.CellInfoWcdma;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.Time;

import com.tencent.stat.StatService;

import org.xmlpull.v1.XmlPullParserException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import collecion.nexd.com.newnexdcollection.activity.CollectionActivity;
import collecion.nexd.com.newnexdcollection.activity.IView.ICollectionActivity;
import collecion.nexd.com.newnexdcollection.adapter.SlidingMenuAdapter;
import collecion.nexd.com.newnexdcollection.modle.FileAttrObject;
import collecion.nexd.com.newnexdcollection.modle.MallInfoObject;
import collecion.nexd.com.newnexdcollection.modle.SensorDataObject;
import collecion.nexd.com.newnexdcollection.presenter.IPresenter.ICollection;
import collecion.nexd.com.newnexdcollection.util.DateUtil;
import collecion.nexd.com.newnexdcollection.util.FileUtil;
import example.com.nexd.collectionsdk.sdk.collector.Collector;
import example.com.nexd.collectionsdk.sdk.collector.CollectorConfig;
import example.com.nexd.collectionsdk.sdk.collector.bean.SensorDataResult;
import example.com.nexd.collectionsdk.sdk.collector.bean.WifiDataResult;
import example.com.nexd.collectionsdk.sdk.collector.listener.SensorCollectorResultListener;
import example.com.nexd.collectionsdk.sdk.collector.listener.WifiCollectorResultListener;
import example.com.nexd.collectionsdk.sdk.collector.util.NexdCollectionAgent;
import example.com.nexd.collectionsdk.sdk.core.TaskExecutor;
import example.com.nexd.collectionsdk.sdk.utils.Log;
import example.com.nexd.collectionsdk.sdk.utils.MD5Util;
import example.com.nexd.collectionsdk.sdk.utils.StepDetector;

/**
 * Created by lawrence on 2015/9/7.
 * 采集业务的业务实现类
 * 1.数据采集
 * 2.传感器监听
 * 3.数据包压缩
 */
public class ICollectionImpl implements ICollection {
    ICollectionActivity iCollectionActivity;
    private List<MallInfoObject> mallInfoObjectList;
    private List<String> cMallNameList;
    //    private LiteOrm liteOrm; // 持有数据库对象
    // 采集数据的索引
    private long indexWifi = 0;
    private long indexSensor = 0;
    private long indexCell = 0;
    private int step = 0;
    private String wifiScanId;
    private String sensScanId;
    private SensorDataObject sensorDataObject;
    private StepDetector stepDetector;
    private double[] temp = new double[3];
    private float[] gyroMatrix;
    // wifi 的回调周期
    private int wifiT = 0;
    private int cellT = 0;
    // sensor 回调周期
    private int sensorT = 0;
    // 内存存储采集到的数据
    private StringBuffer wifiCollection_0;
    private StringBuffer wifiCollection_1;
    private StringBuffer cellCollection_0;
    private StringBuffer cellCollection_1;
    private StringBuffer tempCellCollection;
    private StringBuffer tempStringBuffer;

    private StringBuffer sensCollection_0;
    private StringBuffer sensCollection_1;
    private StringBuffer oldSensorCollection_0;
    private StringBuffer oldSensorCollection_1;
    // 目标文件目录
    private File tarDir;
    private boolean wifiIsFull = false;
    private boolean cellIsFull = false;
    private boolean sensIsFull = false;
    private boolean oldSIsFull = false;
    private FileOutputStream wifiOutputStream;
    private FileOutputStream cellOutputStream;
    private FileOutputStream sensOutputStream;
    private FileOutputStream oldSOutputStream;


    private TelephonyManager manager;
    private String str_start_time;
    private String str_end_time;
    private String str_last_wifi_datas;
    private String str_telephone_imei;
    private long lastDbm;
    private float lastStepCount;

    Context context;
    NexdCollectionAgent nexdCollectionAgent;  // SDK
    private static final String CACHE_PATH = "/Collection/";
    private volatile float[] dataVecotr = new float[70]; // 旧的采集数据采集需要存储数据的对象
    private static final double NS2S = 1.0 / 1000000000.0;
    private final float[] deltaRotationVector = new float[4];
    private long timestamp = 0;
    private Handler handler;
    private long startTimeStamp;

    public ICollectionImpl(ICollectionActivity iCollectionActivity, TelephonyManager manager, Context context, Handler handler) {
        this.iCollectionActivity = iCollectionActivity;
        this.manager = manager;
        this.context = context;
        this.handler = handler;
        gyroMatrix = new float[]{1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f};
    }

    @Override
    public void initSDK() {
        nexdCollectionAgent = NexdCollectionAgent.getInstance();
        nexdCollectionAgent.setContext(context);
        Arrays.fill(dataVecotr, -1);
    }

    @Override
    public void loadSlidilingMenuData(final SlidingMenuAdapter slidingMenuAdapter) {
        /**
         * 1. 是否只检索今天的文件
         */
        TaskExecutor.start(new Runnable() {
            @Override
            public void run() {
                File targetFileDir = new File(Environment.getExternalStorageDirectory().getPath() + "/Collector/");
                if (targetFileDir.isDirectory()) {
                    slidingMenuAdapter.clear();
                    for (File file : targetFileDir.listFiles()) {
                        if (file.getName().contains(".zip")) {
                            slidingMenuAdapter.addData(new FileAttrObject(file, file.getName(), String.valueOf(FileUtil.getFileOrFilesSize(file.getPath(), FileUtil.SIZETYPE_KB))));
                        }
                    }
                    handler.sendEmptyMessage(CollectionActivity.NOTIFYDATASETCHANGE);
                }
            }
        });
    }

    @Override
    public void startCollection(String str_acquisition_cycles, String str_telephone_imei, final String str_city_name, final String str_mall_name, final String str_mall_floor, final String str_user_name) {
        this.str_telephone_imei = str_telephone_imei;
        //  设置采集参数，启动传感器采集和Wifi采集
        CollectorConfig.Builder builder = new CollectorConfig.Builder();
        builder.setCollectionMode(Collector.COLLECTION_MODE_ACTIVE);
        builder.setBluetoothEnable(false);
        builder.setSensorEnable(true);
        builder.setWifiEnable(true);
        builder.setWifiDelay(Integer.parseInt(str_acquisition_cycles), 5000);
        builder.setCollectorDelay(5000);
        builder.setCollectorEnableMode(Collector.bluetooth_enable_mode_auto);
        nexdCollectionAgent.setCollectorConfig(builder.build());
        try {
            startScan();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        // 保存文件名
        String file_name = str_city_name + "_" + str_mall_name + "_" + str_mall_floor + "_" + str_user_name + "_" + str_acquisition_cycles + "_" + str_start_time + "_" + str_end_time;
        Time time = new Time();
        time.setToNow();
        String old_name = "data_" + str_city_name + "_" + str_mall_name + "_" + str_mall_floor + "_" + str_user_name + "_" + time.format2445() + "_" + str_telephone_imei + ".col";
        // 初始化采集用的数据
        this.initCollectionParam(file_name, old_name);

        // 设置回调监听
        nexdCollectionAgent.setWifiCollectorResultListener(new WifiCollectorResultListener() {

            @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
            public void onSuccess(final String scanId, final List<WifiDataResult> wifiDataResults) {
                Log.i("WifiCollectorResultListener", "##onSuccess##-----wifi");
                tempStringBuffer.setLength(0);
                for (int i = 0; i < wifiDataResults.size(); i++) {
                    WifiDataResult scanResult = wifiDataResults.get(i);
                    tempStringBuffer.append(" ");
                    tempStringBuffer.append(scanResult.getBssid()).append(" ");
                    tempStringBuffer.append(scanResult.getLevel());
                }
                tempStringBuffer.append("\n");
                // 不相等换值，更新WifiStringBuffer
                if (!TextUtils.equals(MD5Util.parseStrToMd5U16(tempStringBuffer.toString()), str_last_wifi_datas)) {
                    str_last_wifi_datas = MD5Util.parseStrToMd5U16(tempStringBuffer.toString());

                    if (!wifiIsFull) {
                        wifiCollection_0.append(indexWifi);
                        wifiCollection_0.append(tempStringBuffer);
                    } else {
                        wifiCollection_1.append(indexWifi);
                        wifiCollection_1.append(tempStringBuffer);
                    }
                }
                if (manager.getAllCellInfo() != null && manager.getAllCellInfo().size() > 0) {
                    tempCellCollection.append(indexCell).append(" ");
                    for (CellInfo cellInfo : manager.getAllCellInfo()) {
                        if (cellInfo instanceof CellInfoGsm && ((CellInfoGsm) cellInfo).getCellSignalStrength().getDbm() != lastDbm) {
                            CellInfoGsm gsm = (CellInfoGsm) cellInfo;
                            int cid = gsm.getCellIdentity().getCid(), lac = gsm.getCellIdentity().getLac(),
                                    mcc = gsm.getCellIdentity().getMcc(), mnc = gsm.getCellIdentity().getMnc(), psc = -1;
                            tempCellCollection.append("g" + " " + parseInt(cid) + " " + parseInt(lac) + " " + parseInt(mcc) + " "
                                    + parseInt(mnc) + " " + parseInt(psc) + " " + gsm.getCellSignalStrength().getDbm() + " ");
                            lastDbm = gsm.getCellSignalStrength().getDbm();
                        } else if (cellInfo instanceof CellInfoCdma) {
                            // CellInfoCdma cdma = (CellInfoCdma)ci;
                            // int cid = cdma.getCellIdentity().getCid(), lac =
                            // cdma.getCellIdentity().getLac(), mcc =
                            // cdma.getCellIdentity().getMcc(), mnc =
                            // cdma.getCellIdentity().getMnc(), psc = -1;
                        } else if (cellInfo instanceof CellInfoWcdma && ((CellInfoWcdma) cellInfo).getCellSignalStrength().getDbm() != lastDbm) {
                            CellInfoWcdma wcdma = (CellInfoWcdma) cellInfo;
                            //  采集手机中的各种数据
                            int cid = wcdma.getCellIdentity().getCid(), lac = wcdma.getCellIdentity().getLac(),
                                    mcc = wcdma.getCellIdentity().getMcc(), mnc = wcdma.getCellIdentity().getMnc(),
                                    psc = wcdma.getCellIdentity().getPsc();
                            tempCellCollection.append("w" + " " + parseInt(cid) + " " + parseInt(lac) + " " + parseInt(mcc) + " "
                                    + parseInt(mnc) + " " + parseInt(psc) + " " + wcdma.getCellSignalStrength().getDbm() + " ");
                            lastDbm = wcdma.getCellSignalStrength().getDbm();
                        } else if (cellInfo instanceof CellInfoLte) {
                            // CellInfoLte lte = (CellInfoLte)ci;
                        }
                    }
                    tempCellCollection.append("\n");
                }

                if (!cellIsFull) {
                    cellCollection_0.append(tempCellCollection);
                } else {
                    cellCollection_1.append(tempCellCollection);
                }

                if (wifiT == 10) {
                    try {
                        if (!wifiIsFull) {
                            wifiIsFull = true;
                            writeCashToFile(wifiOutputStream, wifiCollection_0, false);
                        } else {
                            wifiIsFull = false;
                            writeCashToFile(wifiOutputStream, wifiCollection_1, false);
                        }
                        wifiT = 0;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (cellT == 10) {
                    try {
                        if (!cellIsFull) {
                            cellIsFull = true;
                            writeCashToFile(cellOutputStream, cellCollection_0, false);
                        } else {
                            cellIsFull = false;
                            writeCashToFile(cellOutputStream, cellCollection_1, false);
                        }
                        cellT = 0;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                indexCell++;
                indexWifi++;
                cellT++;
                wifiT++;

                Message message = new Message();
                message.what = CollectionActivity.UPDATENVIRONMENTCOUNT; // 更新环境参数数据 数值为集合大小
                message.obj = wifiDataResults.size();
                handler.sendMessage(message);
            }

            private int parseInt(int value) {
                return value == Integer.MAX_VALUE ? -1 : value;
            }

            @Override
            public void onFailed(String scanId, int faied_id, String message) {
                Log.e("WifiCollectorResultListener", "##onFailed## " + faied_id + "  " + message);
            }
        });

        // 设置传感器采集回调监听
        nexdCollectionAgent.setSensorCollectorResultListener(new SensorCollectorResultListener() {

            @Override
            public void onSuccess(final String scanId, final SensorDataResult sensorDataResult) {
                sensScanId = scanId;
                // 将接收到的传感器数据保存在对象中
                saveSensorResultData(scanId, sensorDataResult);
            }

            @Override
            public void onAccuracyChanged(String scanId, Sensor sensor, int accuracy) {

            }

            @Override
            public void onFailed(String scanId, int faied_id, String message) {

            }

        });
    }

    private void initCollectionParam(String file_name, String old_name) {
        step = 0;
        indexWifi = 0;
        indexSensor = 0;
        indexCell = 0;

        // 初始化ping-pong对象， 每次采集重新初始化， 采集结束后，置空
        wifiCollection_0 = new StringBuffer();
        wifiCollection_1 = new StringBuffer();
        cellCollection_0 = new StringBuffer();
        cellCollection_1 = new StringBuffer();
        sensCollection_0 = new StringBuffer();
        sensCollection_1 = new StringBuffer();
        oldSensorCollection_0 = new StringBuffer();
        oldSensorCollection_1 = new StringBuffer();

        tempStringBuffer = new StringBuffer();
        tempCellCollection = new StringBuffer();


        sensorT = 0;
        wifiT = 0;
        cellT = 0;
        str_last_wifi_datas = "";
        sensorDataObject = new SensorDataObject();
        stepDetector = new StepDetector(); // 计步器
        str_start_time = DateUtil.getCurrentByType(DateUtil.MMdd_HH_mm);

        tarDir = new File(Environment.getExternalStorageDirectory().getPath() + "/Collector/" + file_name + "/");
        if (!tarDir.exists()) {
            tarDir.mkdirs();
        }
        // 创建目标文件， 并创建文件对应的输出流
        File wifiFile = new File(tarDir.getPath() + File.separator + file_name + ".wifi");
        File sensFile = new File(tarDir.getPath() + File.separator + file_name + ".newCol");
        File cellFile = new File(tarDir.getPath() + File.separator + file_name + ".cel");
        File oldSensorFile = new File(tarDir.getPath() + File.separator + old_name);
        try {
            if (!wifiFile.exists()) {
                wifiFile.createNewFile();
            } else {
                wifiFile.delete();
                wifiFile.createNewFile();
            }
            wifiOutputStream = new FileOutputStream(wifiFile);
            if (!sensFile.exists()) {
                sensFile.createNewFile();
            } else {
                sensFile.delete();
                sensFile.createNewFile();
            }
            sensOutputStream = new FileOutputStream(sensFile);
            if (!cellFile.exists()) {
                cellFile.createNewFile();
            } else {
                cellFile.delete();
                cellFile.createNewFile();
            }
            cellOutputStream = new FileOutputStream(cellFile);
            if (!oldSensorFile.exists()) {
                oldSensorFile.createNewFile();
            } else {
                oldSensorFile.delete();
                oldSensorFile.createNewFile();
            }
            oldSOutputStream = new FileOutputStream(oldSensorFile);
        } catch (IOException e) {
            StatService.reportException(context, e);
            e.printStackTrace();
        }
    }

    @Override
    public void finishedCollection(final String str_city_name, final String str_mall_name, final String str_mall_floor, final String str_user_name, final String str_acquisition_cycles) {
        Log.d("准备执行最后的文件整合", "准备执行最后的文件整合");

        TaskExecutor.start(new Runnable() {
            @Override
            public void run() {
                // 停止监听回调
                nexdCollectionAgent.setWifiCollectorResultListener(null);
                nexdCollectionAgent.setSensorCollectorResultListener(null);
                // 将文件打包压缩，并将源文件删除
                try {
                    if (!wifiIsFull) {
                        writeCashToFile(wifiOutputStream, wifiCollection_0, true);
                    } else {
                        writeCashToFile(wifiOutputStream, wifiCollection_1, true);
                    }

                    if (!cellIsFull) {
                        writeCashToFile(cellOutputStream, cellCollection_0, true);
                    } else {
                        writeCashToFile(cellOutputStream, cellCollection_1, true);
                    }

                    if (!sensIsFull) {
                        writeCashToFile(sensOutputStream, sensCollection_0, true);
                    } else {
                        writeCashToFile(sensOutputStream, sensCollection_1, true);
                    }

                    if (!oldSIsFull) {
                        writeCashToFile(oldSOutputStream, oldSensorCollection_0, true);
                    } else {
                        writeCashToFile(oldSOutputStream, oldSensorCollection_1, true);
                    }

                    wifiIsFull = false;
                    cellIsFull = false;
                    sensIsFull = false;
                    oldSIsFull = false;

                    // 压缩目标文件
                    Log.d(this.getClass().getSimpleName(), "开始压缩文件");
                    FileUtil.compressFile(tarDir, tarDir.getPath());
                    // 将被压缩的文件删除， 只保留zip文件。
                    FileUtil.deleteFileOrDir(tarDir);
                    handler.sendEmptyMessage(CollectionActivity.SAVEOVER);
                    wifiCollection_0 = null;
                    wifiCollection_1 = null;
                    cellCollection_0 = null;
                    cellCollection_1 = null;
                    sensCollection_0 = null;
                    sensCollection_1 = null;
                    oldSensorCollection_0 = null;
                    oldSensorCollection_1 = null;
                } catch (FileNotFoundException e) {
                    StatService.reportException(context, e);
                    Log.e("文件未找到", e.toString());
                } catch (Exception e) {
                    StatService.reportException(context, e);
                    Log.e("压缩异常", e.toString());
                }
            }
        });
    }

    /**
     * 写传感器数据
     *
     * @param scanId
     * @param sensorDataResult
     */

    private void saveSensorResultData(String scanId, SensorDataResult sensorDataResult) {
        // 存储传感器数据
        sensorDataObject.setIndex(indexSensor);
        switch (sensorDataResult.getSensorType()) {
            case Sensor.TYPE_ACCELEROMETER:
                // 将加速度传感器采集到的数据放入dataVector数组的 11、12、13的位置上
                sensorDataObject.setAccelerometer(sensorDataResult.getValues());
                System.arraycopy(sensorDataResult.getValues(), 0, dataVecotr, 10, 3);
                int step = stepDetector.detect(sensorDataResult.getValues()[2] / SensorManager.STANDARD_GRAVITY);
                sensorDataObject.setStepdetect(step);
                dataVecotr[43] = stepDetector.detect(step);
                if (dataVecotr[43] == 1 || dataVecotr[56] != lastStepCount) {
                    Message message = new Message();
                    message.what = CollectionActivity.UPDATESTEP;
                    message.obj = stepDetector.getStepCount();
                    handler.sendMessage(message);
                    sensorDataObject.setTimestamp(sensorDataResult.getTimestamp());
                    Log.d("Accelerometer", sensorDataResult.getValues().length);
                    lastStepCount = dataVecotr[56];
                }
                break;
            case Sensor.TYPE_LINEAR_ACCELERATION:
                sensorDataObject.setLinear_accelerometer(sensorDataResult.getValues());
                System.arraycopy(sensorDataResult.getValues(), 0, dataVecotr, 13, 3);
                // 线性加速度传感器的数据存储在 14、15、16位置上
                Log.d("TYPE_LINEAR_ACCELERATION", sensorDataResult.getValues().length);
                break;
            case Sensor.TYPE_GYROSCOPE:
                Log.d("TYPE_GYROSCOPE", sensorDataResult.getValues().length);
                // 陀螺仪传感器
                gyroHandler(sensorDataResult.getValues(), sensorDataResult.getTimestamp());
                break;
            case Sensor.TYPE_GRAVITY:
                sensorDataObject.setGravity(sensorDataResult.getValues());
                System.arraycopy(sensorDataResult.getValues(), 0, dataVecotr, 16, 3);
                Log.d("TYPE_GRAVITY", sensorDataResult.getValues().length);
                // 重力加速度传感器 17、18、19
                break;
            case Sensor.TYPE_MAGNETIC_FIELD:
                // 磁力传感器
                sensorDataObject.setMagnetic_field(sensorDataResult.getValues());
                System.arraycopy(sensorDataResult.getValues(), 0, dataVecotr, 25, 3);
                Log.d("TYPE_MAGNETIC_FIELD", sensorDataResult.getValues().length);
                break;
            case Sensor.TYPE_ROTATION_VECTOR:
                // 旋转矢量
                sensorDataObject.setRotation_vector(sensorDataResult.getValues());
                System.arraycopy(sensorDataResult.getValues(), 0, dataVecotr, 28, 3);
                Log.d("TYPE_ROTATION_VECTOR", sensorDataResult.getValues().length);
                break;
            case Sensor.TYPE_ORIENTATION:
                // 方向传感器
                sensorDataObject.setGetOrientation(sensorDataResult.getValues());
                System.arraycopy(sensorDataResult.getValues(), 0, dataVecotr, 31, sensorDataResult.getValues().length);
                Log.d("TYPE_ORIENTATION", sensorDataResult.getValues().length);
                break;
            case Sensor.TYPE_PRESSURE:
                // 压力传感器
                sensorDataObject.setPressure(sensorDataResult.getValues());
                System.arraycopy(sensorDataResult.getValues(), 0, dataVecotr, 35, 1);
                Log.d("TYPE_PRESSURE", sensorDataResult.getValues().length);
                break;
            case Sensor.TYPE_AMBIENT_TEMPERATURE:
                // 温度传感器
                sensorDataObject.setTemperature(sensorDataResult.getValues());
                System.arraycopy(sensorDataResult.getValues(), 0, dataVecotr, 36, 1);
                Log.d("TYPE_AMBIENT_TEMPERATURE", sensorDataResult.getValues().length);
                break;
            case Sensor.TYPE_LIGHT:
                // 光传感器
                sensorDataObject.setLight(sensorDataResult.getValues());
                System.arraycopy(sensorDataResult.getValues(), 0, dataVecotr, 37, 1);
                Log.d("TYPE_LIGHT", sensorDataResult.getValues().length);
                break;

            case Sensor.TYPE_PROXIMITY:
                // 接近传感器
                sensorDataObject.setProximity(sensorDataResult.getValues());
                System.arraycopy(sensorDataResult.getValues(), 0, dataVecotr, 38, 1);
                Log.d("TYPE_PROXIMITY", sensorDataResult.getValues().length);
                break;
            case Sensor.TYPE_RELATIVE_HUMIDITY:
                // 相对湿度
                sensorDataObject.setRelative_humidity(sensorDataResult.getValues());
                System.arraycopy(sensorDataResult.getValues(), 0, dataVecotr, 39, 1);
                Log.d("TYPE_RELATIVE_HUMIDITY", sensorDataResult.getValues().length);
                break;
            case Sensor.TYPE_GAME_ROTATION_VECTOR:
                sensorDataObject.setGame_rotation_vector(sensorDataResult.getValues());
                System.arraycopy(sensorDataResult.getValues(), 0, dataVecotr, 50, 3);
                Log.d("TYPE_GAME_ROTATION_VECTOR", sensorDataResult.getValues().length);
                break;
            case Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR:
                sensorDataObject.setGeomagnetic_rotation_vector(sensorDataResult.getValues());
                System.arraycopy(sensorDataResult.getValues(), 0, dataVecotr, 53, 3);
                Log.d("TYPE_GEOMAGNETIC_ROTATION_VECTOR", sensorDataResult.getValues().length);
                break;
            case Sensor.TYPE_STEP_COUNTER:
                // Android系统的计步器
                sensorDataObject.setStep_counter(sensorDataResult.getValues());
                System.arraycopy(sensorDataResult.getValues(), 0, dataVecotr, 56, 1);
                Log.d("TYPE_STEP_COUNTER", sensorDataResult.getValues().length);
                break;
            case Sensor.TYPE_STEP_DETECTOR:
                break;
            case Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED:
                sensorDataObject.setMagnetic_field_uncalibrated(sensorDataResult.getValues());
                System.arraycopy(sensorDataResult.getValues(), 0, dataVecotr, 57, 6);
                Log.d("TYPE_MAGNETIC_FIELD_UNCALIBRATED", sensorDataResult.getValues().length);
                break;
            case Sensor.TYPE_GYROSCOPE_UNCALIBRATED:
                sensorDataObject.setGyroscope_uncalibrated(sensorDataResult.getValues());
                System.arraycopy(sensorDataResult.getValues(), 0, dataVecotr, 63, 6);
                Log.d("TYPE_GYROSCOPE_UNCALIBRATED", sensorDataResult.getValues().length);
                break;
            case Sensor.TYPE_SIGNIFICANT_MOTION:
                break;
            default:
                break;
        }
        writeOldSensor();
        // 传感器StringBuffer

        if (!sensIsFull) {
            sensCollection_0.append(sensorDataObject.toString());
        } else {
            sensCollection_1.append(sensorDataObject.toString());
        }
        // 计算传感器采集周期   每50次执行一次缓存存储   1s进行一次
        if (sensorT == 50) {
            try {
                if (!sensIsFull) {
                    sensIsFull = true;
                    writeCashToFile(sensOutputStream, sensCollection_0, false);
                } else {
                    sensIsFull = false;
                    writeCashToFile(sensOutputStream, sensCollection_1, false);
                }

                if (!oldSIsFull) {
                    oldSIsFull = true;
                    writeCashToFile(oldSOutputStream, oldSensorCollection_0, false);
                } else {
                    oldSIsFull = false;
                    writeCashToFile(oldSOutputStream, oldSensorCollection_1, false);
                }
                sensorT = 0;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        sensorT++;
        indexSensor++;
    }

    private void writeCashToFile(FileOutputStream outputStream, StringBuffer stringBuffer, boolean isFinish) throws IOException {
        outputStream.write(stringBuffer.toString().getBytes());
        outputStream.flush();
        stringBuffer.setLength(0);
        if (isFinish) {
            outputStream.close();
        }
    }


    private void writeOldSensor() {
        if (!oldSIsFull) {
            oldSensorCollection_0.append(indexSensor).append(" ");
            for (int i = 1; i < 44; i++) {
                oldSensorCollection_0.append(dataVecotr[i]).append(" ");
            }
            oldSensorCollection_0.append(timestamp).append(" ");
            for (int i = 44; i < 69; i++) {
                oldSensorCollection_0.append(dataVecotr[i]).append(" ");
            }
            oldSensorCollection_0.append("\n");
        } else {
            oldSensorCollection_1.append(indexSensor).append(" ");
            for (int i = 1; i < 44; i++) {
                oldSensorCollection_1.append(dataVecotr[i]).append(" ");
            }
            oldSensorCollection_1.append(timestamp).append(" ");
            for (int i = 44; i < 69; i++) {
                oldSensorCollection_1.append(dataVecotr[i]).append(" ");
            }
            oldSensorCollection_1.append("\n");
        }

    }

    // 计算陀螺仪
    protected void gyroHandler(float[] value, long timestamp_e) {
        // This timestep's delta rotation to be multiplied by the current
        // rotation
        // after computing it from the gyro sample data.
        // timestep`s 的值由当前值 * 来自陀螺仪的数据样本
        if (timestamp != 0) {
            final double dT = (double) (timestamp_e - timestamp) * NS2S;
            // Axis of the rotation sample, not normalized yet.
            float axisX = value[0];
            float axisY = value[1];
            float axisZ = value[2];
            sensorDataObject.setGyroscope(value);
            System.arraycopy(value, 0, dataVecotr, 19, 3);
            for (int i = 0; i < 3; i++) {
                temp[i] += (double) value[i] * dT;
                dataVecotr[44 + i] += (double) value[i] * dT;
            }
            sensorDataObject.setGyro_integration(temp);
            Log.d("Gyro_integration", temp.length);
            // Calculate the angular speed of the sample
            float omegaMagnitude = (float) Math.sqrt(axisX * axisX + axisY * axisY + axisZ * axisZ);
            // Normalize the rotation vector if it's big enough to get the
            // axis
            // (that is, EPSILON should represent your maximum allowable
            // margin of error)
            if (omegaMagnitude > Float.MIN_NORMAL) {
                axisX /= omegaMagnitude;
                axisY /= omegaMagnitude;
                axisZ /= omegaMagnitude;
            }
            // Integrate around this axis with the angular speed by the
            // timestep
            // in order to get a delta rotation from this sample over the
            // timestep
            // We will convert this axis-angle representation of the delta
            // rotation
            // into a quaternion before turning it into the rotation matrix.
            float thetaOverTwo = (float) (omegaMagnitude * dT / 2.0f);
            float sinThetaOverTwo = (float) Math.sin(thetaOverTwo);
            float cosThetaOverTwo = (float) Math.cos(thetaOverTwo);
            deltaRotationVector[0] = sinThetaOverTwo * axisX;
            deltaRotationVector[1] = sinThetaOverTwo * axisY;
            deltaRotationVector[2] = sinThetaOverTwo * axisZ;
            deltaRotationVector[3] = cosThetaOverTwo;
        }
        timestamp = timestamp_e;
        float[] deltaRotationMatrix = new float[9];
        float[] orientation = new float[3];
        SensorManager.getRotationMatrixFromVector(deltaRotationMatrix, deltaRotationVector);
        gyroMatrix = matrixMultiplication(gyroMatrix, deltaRotationMatrix);
        SensorManager.getOrientation(gyroMatrix, orientation);
        sensorDataObject.setOrientation(orientation);
        System.arraycopy(orientation, 0, dataVecotr, 22, 3);
        Log.d("orientation", orientation.length);
    }

    private float[] matrixMultiplication(float[] A, float[] B) {
        float[] result = new float[9];

        result[0] = A[0] * B[0] + A[1] * B[3] + A[2] * B[6];
        result[1] = A[0] * B[1] + A[1] * B[4] + A[2] * B[7];
        result[2] = A[0] * B[2] + A[1] * B[5] + A[2] * B[8];

        result[3] = A[3] * B[0] + A[4] * B[3] + A[5] * B[6];
        result[4] = A[3] * B[1] + A[4] * B[4] + A[5] * B[7];
        result[5] = A[3] * B[2] + A[4] * B[5] + A[5] * B[8];

        result[6] = A[6] * B[0] + A[7] * B[3] + A[8] * B[6];
        result[7] = A[6] * B[1] + A[7] * B[4] + A[8] * B[7];
        result[8] = A[6] * B[2] + A[7] * B[5] + A[8] * B[8];

        return result;
    }

    @Override
    public void initDropList(final String city_name) {
        // 异步执行xml文件解析
        TaskExecutor.start(new Runnable() {
            @Override
            public void run() {
                try {
                    if (mallInfoObjectList != null) {
                        mallInfoObjectList.clear();
                        cMallNameList.clear();
                        mallInfoObjectList.addAll(FileUtil.getMallInfo(context, city_name));
                        Collections.sort(mallInfoObjectList, new Comparator<MallInfoObject>() {
                            @Override
                            public int compare(MallInfoObject lft, MallInfoObject rgt) {
                                return lft.geteMallName().compareTo(rgt.geteMallName());
                            }
                        });
                        for (MallInfoObject mallInfoObject : mallInfoObjectList) {
                            cMallNameList.add(mallInfoObject.getcMallName());
                        }
                        handler.sendEmptyMessage(CollectionActivity.LOADMALLINFOSUCCESS);
                    }
                } catch (XmlPullParserException e) {
                    StatService.reportException(context, e);
                    e.printStackTrace();
                } catch (IOException e) {
                    StatService.reportException(context, e);
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void stopCollection() {
        stopScan();
    }


    @Override
    public void setCollectionMessageList(List<MallInfoObject> mallInfoObjectList, List<String> cMallNameList) {
        this.mallInfoObjectList = mallInfoObjectList;
        this.cMallNameList = cMallNameList;
    }

    @Override
    public void startScan() throws IllegalAccessException {
        startTimeStamp = System.currentTimeMillis();
        nexdCollectionAgent.startCollection();
    }

    @Override
    public void stopScan() {
        nexdCollectionAgent.stopCollection();
    }

    @Override
    public void closeDiskLruCache() {

    }
}
